'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { AlertCircle, BookOpen, RotateCcw, TrendingUp, Calendar, Target, CheckCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useAuth } from '@/lib/auth-client'
import { useRouter } from 'next/navigation'

interface Mistake {
  id: number
  topic_id: string
  topic_name: string
  question_index: number
  question_stem: string
  correct_answer: string
  user_answer: string
  solution: string
  wrong_count: number
  reviewed: boolean
  mastered: boolean
  created_at: string
  last_wrong_at: string
  reviewed_at?: string
}

export default function MistakesPage() {
  const [mistakes, setMistakes] = useState<Mistake[]>([])
  const [filteredMistakes, setFilteredMistakes] = useState<Mistake[]>([])
  const [selectedTopic, setSelectedTopic] = useState<string>('')
  const [showMastered, setShowMastered] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  const { user, loading: authLoading } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (!authLoading) {
      if (!user) {
        router.push('/auth/login')
      } else {
        loadMistakes()
      }
    }
  }, [authLoading, user])

  useEffect(() => {
    filterMistakes()
  }, [mistakes, selectedTopic, showMastered])

  const loadMistakes = async () => {
    try {
      setIsLoading(true)
      setError('')

      const token = localStorage.getItem('auth_token')
      if (!token) {
        router.push('/auth/login')
        return
      }

      const response = await fetch('/api/mistakes', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      })

      const data = await response.json()

      if (data.success) {
        setMistakes(data.data?.mistakes || [])
      } else {
        setError(data.error || '加载错题失败')
      }
    } catch (err) {
      console.error('加载错题错误:', err)
      setError('加载错题时发生错误')
    } finally {
      setIsLoading(false)
    }
  }

  const filterMistakes = () => {
    let filtered = mistakes

    // 知识点过滤
    if (selectedTopic) {
      filtered = filtered.filter(m => m.topic_name === selectedTopic)
    }

    // 掌握状态过滤
    if (!showMastered) {
      filtered = filtered.filter(m => !m.mastered)
    }

    setFilteredMistakes(filtered)
  }

  const markAsReviewed = async (mistakeId: number) => {
    try {
      const token = localStorage.getItem('auth_token')
      if (!token) return

      const response = await fetch(`/api/mistakes/${mistakeId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ action: 'review' }),
      })

      const data = await response.json()

      if (data.success) {
        setMistakes(prev => prev.map(m =>
          m.id === mistakeId ? { ...m, reviewed: true } : m
        ))
      }
    } catch (err) {
      console.error('标记已复习错误:', err)
    }
  }

  const markAsMastered = async (mistakeId: number) => {
    try {
      const token = localStorage.getItem('auth_token')
      if (!token) return

      const response = await fetch(`/api/mistakes/${mistakeId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ action: 'master' }),
      })

      const data = await response.json()

      if (data.success) {
        setMistakes(prev => prev.map(m =>
          m.id === mistakeId ? { ...m, mastered: true } : m
        ))
      }
    } catch (err) {
      console.error('标记已掌握错误:', err)
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  }

  const uniqueTopics = Array.from(new Set(mistakes.map(m => m.topic_name)))
  const totalMistakes = mistakes.length
  const masteredCount = mistakes.filter(m => m.mastered).length
  const reviewedCount = mistakes.filter(m => m.reviewed).length

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载错题库中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8 text-center"
        >
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            错题库
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            回顾错题，巩固知识，通过后续练习验证掌握程度
          </p>
          <p className="text-sm text-blue-600 dark:text-blue-400 mt-2">
            💡 点击"标记已复习"后，题目将返回题库，在后续练习中随机出现
          </p>
        </motion.div>

        {/* 错误提示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 rounded-lg bg-red-100 border border-red-300 text-red-700"
          >
            {error}
          </motion.div>
        )}

        <div className="grid lg:grid-cols-4 gap-6">
          {/* 统计信息和筛选 */}
          <div className="lg:col-span-1 space-y-6">
            {/* 错题统计 */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.1 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <TrendingUp className="w-5 h-5" />
                    错题统计
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">总错题</span>
                    <span className="font-bold text-lg text-red-600">{totalMistakes}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">已复习</span>
                    <span className="font-bold text-lg text-blue-600">{reviewedCount}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">已掌握</span>
                    <span className="font-bold text-lg text-green-600">{masteredCount}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">掌握率</span>
                    <span className="font-bold text-lg text-purple-600">
                      {totalMistakes > 0 ? Math.round((masteredCount / totalMistakes) * 100) : 0}%
                    </span>
                  </div>
                </CardContent>
              </Card>
            </motion.div>

            {/* 筛选选项 */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.2 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Target className="w-5 h-5" />
                    筛选选项
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* 知识点筛选 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      知识点
                    </label>
                    <select
                      value={selectedTopic}
                      onChange={(e) => setSelectedTopic(e.target.value)}
                      className="w-full px-3 py-2 rounded-lg bg-white/20 backdrop-blur-sm border border-white/30 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="">全部知识点</option>
                      {uniqueTopics.map(topic => (
                        <option key={topic} value={topic}>{topic}</option>
                      ))}
                    </select>
                  </div>

                  {/* 显示已掌握 */}
                  <div className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      id="showMastered"
                      checked={showMastered}
                      onChange={(e) => setShowMastered(e.target.checked)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <label htmlFor="showMastered" className="text-sm text-gray-700 dark:text-gray-300">
                      显示已掌握错题
                    </label>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* 错题列表 */}
          <div className="lg:col-span-3">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
              className="space-y-6"
            >
              {filteredMistakes.length === 0 ? (
                <Card glassmorphism className="backdrop-blur-xl">
                  <CardContent className="p-12 text-center">
                    <BookOpen className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                    <h3 className="text-xl font-semibold text-gray-600 mb-2">暂无错题</h3>
                    <p className="text-gray-500">
                      {selectedTopic || !showMastered
                        ? '没有找到符合条件的错题'
                        : '恭喜！您还没有错题记录'
                      }
                    </p>
                  </CardContent>
                </Card>
              ) : (
                filteredMistakes.map((mistake, index) => (
                  <motion.div
                    key={mistake.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.1 * index }}
                  >
                    <Card glassmorphism className={`backdrop-blur-xl hover:shadow-lg transition-all duration-300 ${
                      mistake.mastered ? 'opacity-75' : ''
                    }`}>
                      <CardHeader>
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-2">
                              <span className="px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                {mistake.topic_name}
                              </span>
                              {mistake.reviewed && (
                                <span className="px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                  已复习
                                </span>
                              )}
                              {mistake.mastered && (
                                <span className="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                  已掌握
                                </span>
                              )}
                              <span className="px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                错误 {mistake.wrong_count} 次
                              </span>
                            </div>
                            <CardTitle className="text-lg text-gray-800 dark:text-gray-200">
                              {mistake.question_stem}
                            </CardTitle>
                            <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
                              <span className="flex items-center gap-1">
                                <Calendar className="w-4 h-4" />
                                {formatDate(mistake.created_at)}
                              </span>
                            </div>
                          </div>
                          <div className="flex gap-2 ml-4">
                            {!mistake.reviewed && (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => markAsReviewed(mistake.id)}
                              >
                                <RotateCcw className="w-4 h-4 mr-1" />
                                标记已复习
                              </Button>
                            )}
                            {!mistake.mastered && (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => markAsMastered(mistake.id)}
                              >
                                <CheckCircle className="w-4 h-4 mr-1" />
                                标记已掌握
                              </Button>
                            )}
                          </div>
                        </div>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-4">
                          <div>
                            <h4 className="font-medium text-gray-700 dark:text-gray-300 mb-2">您的答案：</h4>
                            <p className="text-sm text-red-600 bg-red-50 p-3 rounded-lg">
                              {mistake.user_answer}
                            </p>
                          </div>

                          <div>
                            <h4 className="font-medium text-gray-700 dark:text-gray-300 mb-2">正确答案：</h4>
                            <p className="text-sm text-green-600 bg-green-50 p-3 rounded-lg">
                              {mistake.correct_answer}
                            </p>
                          </div>

                          {mistake.solution && (
                            <div>
                              <h4 className="font-medium text-gray-700 dark:text-gray-300 mb-2">详细解析：</h4>
                              <p className="text-sm text-gray-600 dark:text-gray-400 bg-blue-50 p-3 rounded-lg whitespace-pre-line">
                                {mistake.solution}
                              </p>
                            </div>
                          )}
                        </div>
                      </CardContent>
                    </Card>
                  </motion.div>
                ))
              )}
            </motion.div>

            {/* 统计信息 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
              className="mt-8"
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-300">
                    <span>
                      显示 {filteredMistakes.length} / {mistakes.length} 道错题
                    </span>
                    <span>
                      最后更新：{new Date().toLocaleDateString()}
                    </span>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}
